package com.fengwk.support.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.fengwk.support.constant.SupportConstant;
import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.LoggerUtils.Logger;

/**
 * 轻量级http工具,用于发送http请求连接
 * 
 * @deprecated use {@link HttpClientUtils}
 */
public class HttpConnectionUtils {
	
	private static Logger LOG = LoggerUtils.getLogger(HttpConnectionUtils.class);
	
	private HttpConnectionUtils() {
		throw new BaseException("can not instance " + getClass());
	}
	
	public static String post(String url) {
		return post(url, "", null);
	}
	
	public static String post(String url, String params) {
		return post(url, params, null);
	}
	
	public static String post(String url, Map<String, String> params) {
		return post(url, params, null);
	}
	
	public static String post(String url, Map<String, String> params, Map<String, String> header) {
		String param = HttpClientUtils.joinParams(params);
		return post(url, param, header);
	}
	
	public static String post(String url, String param, Map<String, String> header) {
		// 输出post
		PrintWriter pw = null;
		BufferedReader br = null;
		String result = "";
		// 请求
		LOG.debug("ready post => " + url + "?" + param);
		
		URL realUrl = null;
		try {
			realUrl = new URL(url);
		} catch (MalformedURLException e) {
		    LOG.error(e);
		}
		// 打开和URL之间的连接
		URLConnection conn = null;
		try {
			conn = realUrl.openConnection();
		} catch (IOException e) {
		    LOG.error(e);
		}
		// 设置通用的请求属性
		if(header != null && header.size() > 0) {
			Iterator<Entry<String, String>> it = header.entrySet().iterator();
			while(it.hasNext()) {
				Entry<String, String> entry = it.next();
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
		}
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		// 发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		// 获取URLConnection对象对应的输出流
		OutputStream os = null;
		try {
			os = conn.getOutputStream();
		} catch (IOException e) {
		    LOG.error(e);
		}
		pw = new PrintWriter(os);
		// 发送请求参数
		pw.print(param);
		pw.flush();
		// 定义BufferedReader输入流来读取URL的响应
		InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
		    LOG.error(e);
		}
		try {
			br = new BufferedReader(new InputStreamReader(is, SupportConstant.DEFAULT_CHARSET));
		} catch (IOException e) {
		    LOG.error(e);
		}
		String line;
		try {
			while ((line = br.readLine()) != null) {
				result += line;
			}
		} catch (IOException e) {
		    LOG.error(e);
		}
		IoUtils.close(is);
		IoUtils.close(os);
		IoUtils.close(pw);
		IoUtils.close(br);
		LOG.debug("post response ==> " + result);
		return result;
	}
	
	public static String get(String url, Map<String, String> params)  {
		String param = HttpClientUtils.joinParams(params);
		if (StringUtils.isNotBlank(param)) {
			url += "?" + param;
		}
		return get(url);
	}
	
	public static String get(String url)  {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("accept", "*/*");
		headers.put("Content-Type", "text/html;charset=UTF-8");
		return get(url, headers, null, null, false);
	}
	
	public static String get(String url, Integer tomeout)  {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("accept", "*/*");
		headers.put("Content-Type", "text/html;charset=UTF-8");
		return get(url, headers, tomeout, tomeout, false);
	}
	
	public static String get(String url, Map<String, String> headers, Integer connecTimeout, Integer readTimeout, Boolean formatLine)  {
	    LOG.debug("ready get => " + url);
		String result = "";
		URLConnection conn = null;
		try {
			conn = (new URL(url)).openConnection();
		} catch (IOException e) {
		    LOG.error(e);
		}
		if(connecTimeout != null) conn.setConnectTimeout(connecTimeout);
		if(readTimeout != null) conn.setReadTimeout(readTimeout);
		if(MapUtils.isNotBlank(headers)) {
			for(String key: headers.keySet()) {
				conn.setRequestProperty(key, headers.get(key));
			}
		}
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		try {
			conn.connect();
		} catch (IOException e) {
		    LOG.error(e);
		}
		InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
		    LOG.error(e);
		}
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(is, SupportConstant.DEFAULT_CHARSET));
		} catch (UnsupportedEncodingException e) {
		    LOG.error(e);
		}
		String line;
		StringBuffer sb = new StringBuffer();
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
				if(formatLine) sb.append("\n\r");
			}
		} catch (IOException e) {
		    LOG.error(e);
		}
		if(sb.length() > 0) {
			result = sb.toString();
			if(formatLine) result = result.replaceAll("\\n\\r$", "");
		}
		IoUtils.close(is);
		IoUtils.close(br);
		LOG.debug("get response ==> " + result);
		return result;
	}
	
	public static String getByProxy(String url, Map<String, String> headers, String proxyHost, Integer proxyPort, Integer timeout)  {
	    LOG.debug("ready get by proxy [" + proxyHost + ":" + proxyPort + "] ==> [" + url + "]");
		String result = "";
		// 创建代理服务器  
        InetSocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理  
        URLConnection conn = null;
		try {
			conn = (new URL(url)).openConnection(proxy);
		} catch (IOException e) {
		    LOG.error(e);
		}
		if(timeout != null) {
			conn.setConnectTimeout(timeout);
			conn.setReadTimeout(timeout);
		}
		if(MapUtils.isNotBlank(headers)) {
			for(String key: headers.keySet()) {
				conn.setRequestProperty(key, headers.get(key));
			}
		}
		try {
			conn.connect();
		} catch (Exception e) {
		    LOG.error(e);
		}
		InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
		    LOG.error(e);
		}
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(is, SupportConstant.DEFAULT_CHARSET));
		} catch (IOException e) {
		    LOG.error(e);
		}
		String line;
		StringBuffer sb = new StringBuffer();
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
		    LOG.error(e);
		}
		if(sb.length() > 0) {
			result = sb.toString();
		}
		IoUtils.close(is);
		IoUtils.close(br);
		return result;
	}
	
	public static String postWithFileMap(String url, Map<String, InputStream> fileMap, Map<String, String> params, Map<String, String> headers, Integer timeout) {
		StringBuffer res = new StringBuffer();
        String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
        if(MapUtils.isNotBlank(params)) {
			for(String key: params.keySet()) {
				url += "?" + key + "=" + params.get(key) + "&";
			}
			url = url.replaceAll("&$", "");
		}
        HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) (new URL(url)).openConnection();
		} catch (IOException e) {
		    LOG.error(e);
		}  
        // 发送POST请求必须设置如下两行 
        conn.setDoOutput(true);  
        conn.setDoInput(true);  
        conn.setUseCaches(false);
        if(timeout != null) {
			conn.setConnectTimeout(timeout);
			conn.setReadTimeout(timeout);
		}
        try {
			conn.setRequestMethod("POST");
		} catch (ProtocolException e) {
		    LOG.error(e);
		}
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
        conn.setRequestProperty("Charsert", "UTF-8");
        if(MapUtils.isNotBlank(headers)) {
			for(String key: headers.keySet()) {
				conn.setRequestProperty(key, headers.get(key));
			}
		}
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        OutputStream os = null;
		try {
			os = new DataOutputStream(conn.getOutputStream());
		} catch (IOException e) {
		    LOG.error(e);
		}  
        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线 
        Iterator<Entry<String, InputStream>> it = fileMap.entrySet().iterator();
        int index = 0;
        while(it.hasNext()) {
        	Entry<String, InputStream> entry = it.next();
        	StringBuffer sb = new StringBuffer();    
            sb.append("--");    
            sb.append(BOUNDARY);    
            sb.append("\r\n");    
            sb.append("Content-Disposition: form-data;name=\"file" + index + "\";filename=\"" + entry.getKey() + "\"\r\n");    
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] data = sb.toString().getBytes();  
            try {
				os.write(data);
			} catch (IOException e) {
			    LOG.error(e);
			}  
            InputStream is = entry.getValue();
            int bytes = 0;  
            byte[] bufferOut = new byte[1024];  
            try {
				while ((bytes = is.read(bufferOut)) != -1) {  
					os.write(bufferOut, 0, bytes);  
				}
			} catch (IOException e) {
			    LOG.error(e);
			}  
            try {
				os.write("\r\n".getBytes());//多个文件时，二个文件之间加入这个
			} catch (IOException e) {
			    LOG.error(e);
			}   
            IoUtils.close(is);
            index ++;
        }
        try {
			os.write(end_data);
		} catch (IOException e) {
		    LOG.error(e);
		}
        try {
			os.flush();
		} catch (IOException e) {
		    LOG.error(e);
		}
        IoUtils.close(os);
        // 定义BufferedReader输入流来读取URL的响应  
        BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), SupportConstant.DEFAULT_CHARSET));
		} catch (IOException e) {
		    LOG.error(e);
		}  
        String line = null;  
        try {
			while ((line = reader.readLine()) != null) {  
				res.append(line); 
			}
		} catch (IOException e) {
		    LOG.error(e);
		}
        return res.toString();
    }
	
	public static byte[] getWithBytes(String url, Integer timeout) {
		URLConnection conn = null;
		try {
			conn = (new URL(url)).openConnection();
		} catch (IOException e) {
		    LOG.error(e);
		}
		if(timeout != null) {
			conn.setConnectTimeout(timeout);
			conn.setReadTimeout(timeout);
		}
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		try {
			conn.connect();
		} catch (IOException e) {
		    LOG.error(e);
		}
		InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
		    LOG.error(e);
		}
		byte[] res = IoUtils.toBytes(is);
		IoUtils.close(is);
		return res;
	}
	
}
